package com.ys.controller.api.outer;


import com.ys.config.MenuId;
import com.ys.config.MyConfig;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.finance.TcwPartnerBankInfo;
import com.ys.entity.flow.YspModel;
import com.ys.entity.purchase.*;
import com.ys.entity.sys.TbCompanyBankInfo;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.purchase.*;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgPurchaseContractService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.DateUtil;
import com.ys.util.RedisUtil;
import com.ys.util.excel.ReadExcel;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api/outer/apiOuterDemoLzmBaoGuan")
public class ApiOuterDemoLzmBaoGuanController {

    private static final Logger logger = LoggerFactory.getLogger(ApiOuterDemoLzmBaoGuanController.class);

	private static String URLAPI2_0 = MyConfig.getUrlApi1_5();

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private TcgPurchaseContractMapper tcgPurchaseContractMapper;

	@Autowired
	private YspTaskService yspTaskService;


	@Autowired
	private CommonApiService<TcgPurchaseContract> commonApiService;


	@Autowired
	private TcgPurchaseContractService tcgPurchaseContractService;


	@Autowired
	private TcgPurchaseContractItemMapper tcgPurchaseContractItemMapper;

	@Autowired
	private TcgPurchaseAppointOrderProductComponentMapper tcgPurchaseAppointOrderProductComponentMapper;

	@Autowired
	private TcgInvoiceOffsetMapper tcgInvoiceOffsetMapper;

	@Autowired
	private TcgInvoiceOffsetItemMapper tcgInvoiceOffsetItemMapper;


	@Autowired
	private CommonApiService<TcgInvoiceOffset> commonApiServiceByTcgInvoiceOffset;


	@Autowired
	private CommonApiService<TcgInvoiceRegist> commonApiServiceByTcgInvoiceRegist;


	@Autowired
	private TcgInvoiceRegistMapper tcgInvoiceRegistMapper;

	@Autowired
	private TcgInvoiceRegistItemMapper tcgInvoiceRegistItemMapper;



	/**
	 * 手动刷取采购合同数据
	 */
	@RequestMapping("/test1")
    @ResponseBody
	public R test1(HttpServletRequest request, HttpServletResponse response
			) {
		try {
			logger.info("*************开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("D:/data/采购合同单(1).xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream,0);
			System.out.println("res:\n"+res);

			//母表信息
			List<Map<String,Object>> mList = new ArrayList<>();
			//子表信息
			List<Map<String,Object>> sonList = new ArrayList<>();
			for(int i=1;i<res.size();i++){
				String a1 = res.get(i).get(0);//购买方公司名称
				String a2 = res.get(i).get(1);//供应方公司名称
				String a3 = res.get(i).get(2);//预约采购单单号
				String a4 = res.get(i).get(3);//子件编码
				String a5 = res.get(i).get(4);//子件采购单价

				Map<String,Object> mapNew = new HashMap<>();
				mapNew.put("a1",a1);
				mapNew.put("a2",a2);
				mapNew.put("a3",a3);
				mapNew.put("a4",a4);
				mapNew.put("a5",a5);
				sonList.add(mapNew);
			}

			for(int i=0;i<sonList.size();i++){
				if(i==0){
					mList.add(sonList.get(i));
				}else {
					boolean isAdded = false;
					for(Map<String,Object> mItem:mList){
						//根据a1、a2去重
						if(mItem.get("a1").toString().equals(sonList.get(i).get("a1"))
						&& mItem.get("a2").toString().equals(sonList.get(i).get("a2"))){
							isAdded = true;
						}
					}
					if(!isAdded){
						mList.add(sonList.get(i));
					}
				}
			}
			System.out.println("母表:");
			System.out.println(mList);
			System.out.println("子表:");
			System.out.println(sonList);

			for (Map<String,Object> mItem:mList){
				String a1 = mItem.get("a1").toString();//购买方公司名称
				String a2 = mItem.get("a2").toString();//供应方公司名称

				TbCompanyBankInfo bankInfo = new TbCompanyBankInfo()
						.addLeftJoin("TB_CompanyInfo B on  B.Vid = A.CompanyInfoVid")
						.addField("B.Vname companyVname")
						.addField("B.Tax tax")
						.setVid(a1)
						//.where("B.Vname = '"+a1+"'")
						.queryFirst();

				TcwPartnerBankInfo p111 = new TcwPartnerBankInfo()
						//.setPartnerName(a2)
						.setVid(a2)
						.queryFirst();


				//填入母表信息
				TcgPurchaseContract entity = new TcgPurchaseContract();
				String bid = commonApiService.getCommonNextBid(MenuId.TCG_PurchaseContract);
				entity.setBid(bid);
				entity.setStatus(1);//状态
				entity.setEffectStock(0);//审批状态
				entity.setContractFile("0个附件");
				entity.setCompanyBankInfoId(bankInfo.getId());
				entity.setCompanyInfoVid(bankInfo.getCompanyInfoVid());
				entity.setPartnerBankInfoId(p111.getId());

				//获取制单人信息
				TsUserChange tsUserChange = new TsUserChange().setUserId("admin").setStatus(1).queryFirst();
				entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息


				BigDecimal contractAmount = BigDecimal.ZERO;//合同金额
				//保存子表信息
				for (Map<String,Object> sItem:sonList){
					if(sItem.get("a1").toString().equals(a1) && sItem.get("a2").toString().equals(a2)){

						String a3 = sItem.get("a3").toString();//预约采购单单号
						String a4 = sItem.get("a4").toString();//子件编码
						String a5 = sItem.get("a5").toString();//子件采购单价

						TcgPurchaseContractItem sonEntity = new TcgPurchaseContractItem();
						sonEntity.setPbid(bid);
						sonEntity.setStatus(1);

						TcgPurchaseAppointOrderProductComponent b1 = new TcgPurchaseAppointOrderProductComponent()
								.addLeftJoin("TCG_PurchaseAppointOrderItem I ON I.Id = A.Pid")
								.where("I.Pbid = '"+a3+"'")
								.setSubCode(a4)
								.queryFirst();

						if(b1==null){

							logger.info("！！！！！！！！！！未查询到采购单信息"+a3+"；"+a4);
							throw new IllegalArgumentException("未查询到采购单信息");
							//return R.error();
						}
						BigDecimal purchaseTotalPrice = new BigDecimal(a5).multiply(new BigDecimal(b1.getSubReserveNumber()));//子件采购总价
						contractAmount = contractAmount.add(purchaseTotalPrice);

						sonEntity.setOrderProductComponentId(b1.getId());
						sonEntity.setSubBomNumber(b1.getSubBomNumber());//子件BOM数量

						sonEntity.setSubPurchaseNum(b1.getSubReserveNumber());//子件采购数量
						sonEntity.setSubPurchasePrice(new BigDecimal(a5));//子件采购单价
						sonEntity.setPurchaseTotalPrice(purchaseTotalPrice);//子件采购总价
						sonEntity.setSubPaymentNum(0);//
						sonEntity.setSubWarehousingNum(0);//
						sonEntity.setSubWriteOffNum(0);//
						sonEntity.setSubPreWarehousingNum(0);//

						sonEntity.setSubPaymentState(0);
						sonEntity.setSubWarehousingState(0);
						sonEntity.setSubWriteOffState(0);
						sonEntity.setCancelState(1);

						tcgPurchaseContractItemMapper.insert(sonEntity);
					}
				}


				entity.setContractAmount(contractAmount);

				//新增母表信息
				tcgPurchaseContractMapper.insert(entity);

				//生成审批流程
				YsMenu ysMenu = new YsMenu().setId(MenuId.TCG_PurchaseContract).queryFirst();
				if (ysMenu.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					String createUserId = ShiroUtils.getUserId();
					yspTaskService.init(codeModel, entity.getBid(), createUserId);
				}

				//自动审批
				flowPass(entity);
				flowPass(entity);

			}

			logger.info("*************完成*************");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			//return R.error("操作失败!");
			throw new IllegalArgumentException("操作失败");
		}
	}



	/**
	 * 手动刷取采购合同数据
	 */
	@RequestMapping("/test0")
	@ResponseBody
	public R test0(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("*************开始*************");
			List<TcgPurchaseContract> list1 = new TcgPurchaseContract().setBid("CGHT-241030-1003").queryList();
			for(TcgPurchaseContract entity :list1 ){
				//生成审批流程
				YsMenu ysMenu = new YsMenu().setId(MenuId.TCG_PurchaseContract).queryFirst();
				if (ysMenu.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					String createUserId = ShiroUtils.getUserId();
					yspTaskService.init(codeModel, entity.getBid(), createUserId);
				}
				//自动审批
				flowPass(entity);
				flowPass(entity);
			}
			logger.info("*************完成*************");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			//return R.error("操作失败!");
			throw new IllegalArgumentException("操作失败");
		}
	}




	public R flowPass(TcgPurchaseContract entity) throws  Exception{
		//获取单据信息
		String bid = entity.getBid();

		//获取子表信息
		List<Map<String,Object>> itemList = tcgPurchaseContractService.getItemListByBid(bid);

		if(itemList == null || itemList.size()<=0){
			//return R.error("该单据列表不存在,请核实后再操作!");
			throw new IllegalArgumentException("该单据列表不存在,请核实后再操作!");
		}

		String loginUserId = ShiroUtils.getUserId();
		Flow f = yspTaskService.flowPass(entity.getBid(),loginUserId);

		if (f.getCode() == Flow.Code.FAILED.value) {
			return R.error(f.getMsg());
		} else {
			if (f.getState() == Flow.State.FINISH.value) {
				YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
				if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
					//return R.error("审批状态有误");
					throw new IllegalArgumentException("审批状态有误");
				}
				Date theDate = new Date();
				entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
				entity.setUpdateTime(theDate);


				if(itemList!=null && itemList.size()>0) {
					for (Map<String, Object> item : itemList) {
						String subPurchaseNum = item.get("subPurchaseNum").toString();//子件采购数量
						//****4、回填预约采购管理-预约采购完整性****
						TcgPurchaseAppointOrderProductComponent tcgPurchaseAppointOrderProductComponent = new TcgPurchaseAppointOrderProductComponent();
						tcgPurchaseAppointOrderProductComponent.setId(Long.parseLong(item.get("orderProductComponentId").toString()));
						tcgPurchaseAppointOrderProductComponent.setStateAppointPurchase(1);//修改完整性-0否1是
						tcgPurchaseAppointOrderProductComponent.setSubPurchaseNumber(Integer.parseInt(subPurchaseNum));//子件采购数量
						tcgPurchaseAppointOrderProductComponentMapper.update(tcgPurchaseAppointOrderProductComponent);
					}
				}


				//修改信息
				tcgPurchaseContractMapper.update(entity);
			}
			return R.ok();
		}
	}






	/**
	 * 手动刷取发票数据
	 */
	@RequestMapping("/test2")
	@ResponseBody
	public R test2(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("*************开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("D:/data/发票111.xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream,0);
			System.out.println("res:\n"+res);

			//列表信息
			List<Map<String,Object>> infoList = new ArrayList<>();
			List<Map<String,Object>> sonList = new ArrayList<>();
			for(int i=1;i<res.size();i++){
				String a1 = res.get(i).get(0);//购买方账户编码
				String a2 = res.get(i).get(1);//供应方账户编码
				String a3 = res.get(i).get(2);//货源所在地
				String a4 = res.get(i).get(3);//发票号码
				String a5 = res.get(i).get(4);//开票时间
				String a6 = res.get(i).get(5);//统一税点
				String a7 = res.get(i).get(6);//不含税金额
				String a8 = res.get(i).get(7);//税额
				String a9 = res.get(i).get(8);//含税金额
				String a10 = res.get(i).get(9);//采购合同单号
				String a11 = res.get(i).get(10);//子件编码
				String a12 = res.get(i).get(11);//子件单价
				String a13 = res.get(i).get(12);//发票本次核销数量
				String a14 = res.get(i).get(13);//已报关数量

				Map<String,Object> mapNew = new HashMap<>();
				mapNew.put("a1",a1);
				mapNew.put("a2",a2);
				mapNew.put("a3",a3);
				mapNew.put("a4",a4);
				mapNew.put("a5",DateUtil.getYYYY_MM_DD(DateUtil.addDays("1900-01-01",Math.round(Float.parseFloat(a5)))));
				mapNew.put("a6",a6);
				mapNew.put("a7",a7);
				mapNew.put("a8",a8);
				mapNew.put("a9",a9);
				mapNew.put("a10",a10);
				mapNew.put("a11",a11);
				mapNew.put("a12",a12);
				mapNew.put("a13",a13);
				mapNew.put("a14",a14);
				sonList.add(mapNew);
			}


			for(int i=0;i<sonList.size();i++){
				if(i==0){
					infoList.add(sonList.get(i));
				}else {
					boolean isAdded = false;
					for(Map<String,Object> mItem:infoList){
						//根据a1、a2去重
						if(mItem.get("a1").toString().equals(sonList.get(i).get("a1"))
								&& mItem.get("a2").toString().equals(sonList.get(i).get("a2"))
								&& mItem.get("a4").toString().equals(sonList.get(i).get("a4"))){
							isAdded = true;
						}
					}
					if(!isAdded){
						infoList.add(sonList.get(i));
					}
				}
			}
			System.out.println("列表:");
			System.out.println(infoList);
			System.out.println("子表:");
			System.out.println(sonList);

            int count = 0;
			for(Map<String,Object> item:infoList){
				String a1 = item.get("a1").toString();//购买方账户编码
				String a2 = item.get("a2").toString();//供应方账户编码
				String a3 = item.get("a3").toString();//货源所在地
				String a4 = item.get("a4").toString();//发票号码
				String a5 = item.get("a5").toString();//开票时间
				String a6 = item.get("a6").toString();//统一税点
				String a7 = item.get("a7").toString();//不含税金额
				String a8 = item.get("a8").toString();//税额
				String a9 = item.get("a9").toString();//含税金额

				TbCompanyBankInfo bankInfo = new TbCompanyBankInfo()
						.addLeftJoin("TB_CompanyInfo B on  B.Vid = A.CompanyInfoVid")
						.addField("B.Vname companyVname")
						.addField("B.Tax tax")
						.setVid(a1)
						.queryFirst();

				List<TcwPartnerBankInfo> p111 = new TcwPartnerBankInfo()
						.where("A.Vid = '"+a2+"'")
						.queryList();

				//发票预审核导入

				//填入母表信息
				TcgInvoiceOffset entity = new TcgInvoiceOffset();
				String bid = commonApiServiceByTcgInvoiceOffset.getCommonNextBid(MenuId.TCG_InvoiceOffset);
				entity.setBid(bid);
				entity.setStatus(1);//状态
				entity.setEffectStock(0);//审批状态

				//获取制单人信息
				TsUserChange tsUserChange = new TsUserChange().setUserId("admin").setStatus(1).queryFirst();
				entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息

				entity.setCompanyVid(bankInfo.getCompanyInfoVid());

				entity.setPartnerBankInfoId(p111.get(0).getId());
				entity.setSourceAddress(a3);
				entity.setInvoiceState(1);
				//entity.setCustomsState(a13.equals(a14)?1:0);
				entity.setBackTaxState(0);

				BigDecimal offsetTotalAmount = BigDecimal.ZERO;


				for(Map<String,Object> sItem:sonList){

					//根据a1、a2去重
					if(sItem.get("a1").toString().equals(a1)
							&& sItem.get("a2").toString().equals(a2)
							&& sItem.get("a4").toString().equals(a4)){

                        count++;
                        System.out.println(count);
                        System.out.println(sItem);
						String a10 = sItem.get("a10").toString();//采购合同单号
						String a11 = sItem.get("a11").toString();//子件编码
						String a12 = sItem.get("a12").toString();//子件单价
						String a13 = sItem.get("a13").toString();//发票本次核销数量
						String a14 = sItem.get("a14").toString();//已报关数量

						TcgInvoiceOffsetItem sonEntity = new TcgInvoiceOffsetItem();
						sonEntity.setStatus(1);
						sonEntity.setPbid(bid);
						TcgPurchaseContractItem contractItem = new TcgPurchaseContractItem()
								.addLeftJoin("TCG_PurchaseAppointOrderProductComponent B ON B.Id = A.OrderProductComponentId")
								.setPbid(a10)
								.where("B.SubCode = '"+a11+"'")
								.queryFirst();

						TpProductActiveComponent activeComponent = new TpProductActiveComponent()
								.setCode(a11)
								.queryFirst();

						sonEntity.setPurchaseContractItemId(contractItem.getId());
						sonEntity.setInvoiceModelNo(activeComponent.getInvoiceModelNo());
						sonEntity.setInvoiceName(activeComponent.getInvoiceName());
						sonEntity.setOffsetNum(Math.round(Float.parseFloat(a13)));
						BigDecimal offsetAmount =( new BigDecimal(a12).multiply(new BigDecimal(a13))).setScale(2, RoundingMode.HALF_UP);//本次核销金额 = 发票本次核销数量*子件采购单价
						offsetTotalAmount = offsetTotalAmount.add(offsetAmount);
						sonEntity.setOffsetAmount(offsetAmount);
						sonEntity.setCustomsNum(Math.round(Float.parseFloat(a14)));
						int customsState = 0;
						if(new BigDecimal(a13).compareTo(new BigDecimal(a14))==0){
							customsState = 1;
						}
						sonEntity.setCustomsState(customsState);
						tcgInvoiceOffsetItemMapper.insert(sonEntity);

					}
				}
				entity.setOffsetTotalAmount(offsetTotalAmount);

				tcgInvoiceOffsetMapper.insert(entity);




				TcgInvoiceRegist bEntity = new TcgInvoiceRegist();
				String bidByB =commonApiServiceByTcgInvoiceRegist.getCommonNextBid(MenuId.TCG_InvoiceRegist);
				bEntity.setBid(bidByB);
				bEntity.setStatus(1);//状态
				bEntity.setEffectStock(0);//审批状态
				bEntity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
				bEntity.setInvoiceOffsetId(entity.getId());
				bEntity.setAnnexFile("0个附件");
				bEntity.setInvoiceNo(a4);
				bEntity.setInvoiceDay(a5);
				bEntity.setTaxPercent(new BigDecimal(a6));
				bEntity.setAmountNoTax(new BigDecimal(a7));
				bEntity.setTax(new BigDecimal(a8));
				bEntity.setAmountWithTax(new BigDecimal(a9));


				tcgInvoiceRegistMapper.insert(bEntity);


				List<TcgInvoiceOffsetItem> itemList = new TcgInvoiceOffsetItem()
						.setPbid(bid)
						.queryList();

				for(TcgInvoiceOffsetItem itemOffset:itemList){
					TcgInvoiceRegistItem entityByS = new TcgInvoiceRegistItem();
					entityByS.setPbid(bidByB);
					entityByS.setStatus(1);
					entityByS.setInvoiceOffsetItemId(itemOffset.getId());

					//子件总额（不含税）= 本次核销金额/统一税点(母表字段）
					BigDecimal subTotalPriceNoTax = itemOffset.getOffsetAmount().divide(bEntity.getTaxPercent().add(BigDecimal.ONE),2,BigDecimal.ROUND_HALF_UP);
					entityByS.setSubTotalPriceNoTax(subTotalPriceNoTax);

					//子件单价（不含税） = 子件总额（不含税）/子件数量
					BigDecimal subSinglePriceNoTax = subTotalPriceNoTax.divide(new BigDecimal(itemOffset.getOffsetNum()),2,BigDecimal.ROUND_HALF_UP);
					entityByS.setSubSinglePriceNoTax(subSinglePriceNoTax);
					tcgInvoiceRegistItemMapper.insert(entityByS);
				}



			}





			logger.info("*************完成*************");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}
	}


	/**
	 * 手动刷取发票数据
	 */
	@RequestMapping("/test3")
	@ResponseBody
	public R test3(HttpServletRequest request, HttpServletResponse response){
		try{
			logger.info("*************11111*************");
			List<TcgInvoiceOffset> list1 = new TcgInvoiceOffset().queryList();
			for(TcgInvoiceOffset entity :list1 ){
				//生成审批流程
				YsMenu ysMenu = new YsMenu().setId(MenuId.TCG_InvoiceOffset).queryFirst();
				if (ysMenu.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					String createUserId = ShiroUtils.getUserId();
					yspTaskService.init(codeModel, entity.getBid(), createUserId);
				}

				//审批两次
				flowPassByIa(entity.getId());
				flowPassByIa(entity.getId());
			}

			List<TcgInvoiceRegist> list2 = new TcgInvoiceRegist().queryList();
			for(TcgInvoiceRegist entity :list2 ){
				//生成审批流程
				YsMenu ysMenu2 = new YsMenu().setId(MenuId.TCG_InvoiceRegist).queryFirst();
				if (ysMenu2.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu2.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					String createUserId = ShiroUtils.getUserId();
					yspTaskService.init(codeModel, entity.getBid(), createUserId);
				}

				//审批两次
				flowPassByIb(entity.getBid());
				flowPassByIb(entity.getBid());
			}
			logger.info("*************完成*************");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}
	}




	/**
	 * 手动刷取发票数据
	 */
	@RequestMapping("/test4")
	@ResponseBody
	public R test4(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("*************开始*************");
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("D:/data/1111.xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream,0);
			System.out.println("res:\n"+res);

			//列表信息
			List<Map<String,Object>> infoList = new ArrayList<>();
			List<Map<String,Object>> sonList = new ArrayList<>();
			for(int i=1;i<res.size();i++){
				String a1 = res.get(i).get(0);//购买方账户编码
				String a2 = res.get(i).get(1);//供应方账户编码
				String a3 = res.get(i).get(2);//货源所在地
				String a10 = res.get(i).get(3);//采购合同单号
				String a11 = res.get(i).get(4);//子件编码
				String a12 = res.get(i).get(5);//子件单价
				String a13 = res.get(i).get(6);//发票本次核销数量
				String a14 = "0";//已报关数量

				Map<String,Object> mapNew = new HashMap<>();
				mapNew.put("a1",a1);
				mapNew.put("a2",a2);
				mapNew.put("a3",a3);
				mapNew.put("a10",a10);
				mapNew.put("a11",a11);
				mapNew.put("a12",a12);
				mapNew.put("a13",a13);
				mapNew.put("a14",a14);
				sonList.add(mapNew);
			}


			for(int i=0;i<sonList.size();i++){
				if(i==0){
					infoList.add(sonList.get(i));
				}else {
					boolean isAdded = false;
					for(Map<String,Object> mItem:infoList){
						//根据a1、a2去重
						if(mItem.get("a1").toString().equals(sonList.get(i).get("a1"))
								&& mItem.get("a2").toString().equals(sonList.get(i).get("a2"))){
							isAdded = true;
						}
					}
					if(!isAdded){
						infoList.add(sonList.get(i));
					}
				}
			}
			System.out.println("列表:");
			System.out.println(infoList);
			System.out.println("子表:");
			System.out.println(sonList);

			int count = 0;
			for(Map<String,Object> item:infoList){
				String a1 = item.get("a1").toString();//购买方账户编码
				String a2 = item.get("a2").toString();//供应方账户编码
				String a3 = item.get("a3").toString();//货源所在地

				TbCompanyBankInfo bankInfo = new TbCompanyBankInfo()
						.addLeftJoin("TB_CompanyInfo B on  B.Vid = A.CompanyInfoVid")
						.addField("B.Vname companyVname")
						.addField("B.Tax tax")
						.setVid(a1)
						.queryFirst();

				List<TcwPartnerBankInfo> p111 = new TcwPartnerBankInfo()
						.where("A.Vid = '"+a2+"'")
						.queryList();

				//发票预审核导入

				//填入母表信息
				TcgInvoiceOffset entity = new TcgInvoiceOffset();
				String bid = commonApiServiceByTcgInvoiceOffset.getCommonNextBid(MenuId.TCG_InvoiceOffset);
				entity.setBid(bid);
				entity.setStatus(1);//状态
				entity.setEffectStock(0);//审批状态

				//获取制单人信息
				TsUserChange tsUserChange = new TsUserChange().setUserId("admin").setStatus(1).queryFirst();
				entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息

				entity.setCompanyVid(bankInfo.getCompanyInfoVid());

				entity.setPartnerBankInfoId(p111.get(0).getId());
				entity.setSourceAddress(a3);
				entity.setInvoiceState(1);
				//entity.setCustomsState(a13.equals(a14)?1:0);
				entity.setBackTaxState(0);

				BigDecimal offsetTotalAmount = BigDecimal.ZERO;


				for(Map<String,Object> sItem:sonList){

					//根据a1、a2去重
					if(sItem.get("a1").toString().equals(a1)
							&& sItem.get("a2").toString().equals(a2)){

						count++;
						System.out.println(count);
						System.out.println(sItem);
						String a10 = sItem.get("a10").toString();//采购合同单号
						String a11 = sItem.get("a11").toString();//子件编码
						String a12 = sItem.get("a12").toString();//子件单价
						String a13 = sItem.get("a13").toString();//发票本次核销数量
						String a14 = "0";//已报关数量

						TcgInvoiceOffsetItem sonEntity = new TcgInvoiceOffsetItem();
						sonEntity.setStatus(1);
						sonEntity.setPbid(bid);
						TcgPurchaseContractItem contractItem = new TcgPurchaseContractItem()
								.addLeftJoin("TCG_PurchaseAppointOrderProductComponent B ON B.Id = A.OrderProductComponentId")
								.setPbid(a10)
								.where("B.SubCode = '"+a11+"'")
								.queryFirst();

						TpProductActiveComponent activeComponent = new TpProductActiveComponent()
								.setCode(a11)
								.queryFirst();

						sonEntity.setPurchaseContractItemId(contractItem.getId());
						sonEntity.setInvoiceModelNo(activeComponent.getInvoiceModelNo());
						sonEntity.setInvoiceName(activeComponent.getInvoiceName());
						sonEntity.setOffsetNum(Math.round(Float.parseFloat(a13)));
						BigDecimal offsetAmount =( new BigDecimal(a12).multiply(new BigDecimal(a13))).setScale(2, RoundingMode.HALF_UP);//本次核销金额 = 发票本次核销数量*子件采购单价
						offsetTotalAmount = offsetTotalAmount.add(offsetAmount);
						sonEntity.setOffsetAmount(offsetAmount);
						sonEntity.setCustomsNum(Math.round(Float.parseFloat(a14)));
						int customsState = 0;
						if(new BigDecimal(a13).compareTo(new BigDecimal(a14))==0){
							customsState = 1;
						}
						sonEntity.setCustomsState(customsState);
						tcgInvoiceOffsetItemMapper.insert(sonEntity);

					}
				}
				entity.setOffsetTotalAmount(offsetTotalAmount);
				tcgInvoiceOffsetMapper.insert(entity);
			}

			logger.info("*************完成*************");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}
	}


	/**
	 * 手动刷取发票数据
	 */
	@RequestMapping("/test5")
	@ResponseBody
	public R test5(HttpServletRequest request, HttpServletResponse response){
		try{
			logger.info("*************11111*************");
			List<TcgInvoiceOffset> list1 = new TcgInvoiceOffset().setEffectStock(0).queryList();
			for(TcgInvoiceOffset entity :list1 ){
				//生成审批流程
				YsMenu ysMenu = new YsMenu().setId(MenuId.TCG_InvoiceOffset).queryFirst();
				if (ysMenu.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					String createUserId = ShiroUtils.getUserId();
					yspTaskService.init(codeModel, entity.getBid(), createUserId);
				}

				//审批两次
				flowPassByIa(entity.getId());
				flowPassByIa(entity.getId());
			}

			logger.info("*************完成*************");
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}
	}






	public R flowPassByIb(String bid) throws Exception {
		String loginUserId = ShiroUtils.getUserId();
		// 若流程是初始化状态，需验证子表核销总额 = 母表含税金额
		YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
		TcgInvoiceRegist tcgInvoiceRegist = null;
		if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
			tcgInvoiceRegist = new TcgInvoiceRegist().setBid(bid).queryFirst();

			TcgInvoiceOffset tcgInvoiceOffset = new TcgInvoiceOffset().setId(tcgInvoiceRegist.getInvoiceOffsetId()).queryFirst();

			/*
			if (tcgInvoiceRegist.getAmountWithTax().compareTo(tcgInvoiceOffset.getOffsetTotalAmount()) != 0) {
				return R.error("核销总额与含税金额不一致");
			}

			 */
		}

		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else if (f.getState() == Flow.State.FINISH.value) {
				flowFinishByIb(bid);
			}
			return R.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}



	public void flowFinishByIb(String bid) throws Exception {

		TcgInvoiceRegist entity = new TcgInvoiceRegist().setBid(bid).queryFirst();

		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}

		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		tcgInvoiceRegistMapper.update(entity);

	}


	public R flowPassByIa(Long id) throws Exception {
		//获取单据信息
		TcgInvoiceOffset entity = new TcgInvoiceOffset().setId(id).queryFirst();
		if (entity == null) {
			return R.error("该单据不存在,请核实后再操作!");
		}

		String loginUserId = ShiroUtils.getUserId();
		Flow f = yspTaskService.flowPass(entity.getBid(),loginUserId);

		if (f.getCode() == Flow.Code.FAILED.value) {
			return R.error(f.getMsg());
		} else {
			if (f.getState() == Flow.State.FINISH.value) {
				return flowFinishByIa(entity);
			}
			return R.ok();
		}
	}


	public R flowFinishByIa(TcgInvoiceOffset entity) throws Exception {

		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return R.error("状态有误");
		}
		Date theDate = new Date();
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		entity.setUpdateTime(theDate);

		//获取子表信息
		List<TcgInvoiceOffsetItem> itemList = new TcgInvoiceOffsetItem().setPbid(entity.getBid()).queryList();
		if(itemList==null || itemList.size()<=0){
			return R.error("未查询到对应的子表信息");
		}

		//拼接采购合同id
		String contractIds = "";
		for( TcgInvoiceOffsetItem item:itemList ){
			if(contractIds.equals("")){
				contractIds = item.getPurchaseContractItemId().toString();
			}else {
				contractIds = contractIds + ","+ item.getPurchaseContractItemId().toString();
			}
		}

		//获取采购合同信息
		List<TcgPurchaseContractItem> tcgPurchaseContractItemList = new TcgPurchaseContractItem()
				.where("A.Id IN (" + contractIds + ")")
				.queryList();
		if(tcgPurchaseContractItemList==null || tcgPurchaseContractItemList.size()<=0){
			return R.error("未查询到采购合同信息");
		}

		//变更采购合同管理数据字段
		//遍历详情信息
		for (int i=0;i<itemList.size();i++){
			TcgInvoiceOffsetItem item = itemList.get(i);
			//获取对应的采购合同信息
			List<TcgPurchaseContractItem> contractItemListById = tcgPurchaseContractItemList.stream()
					.filter(contractItem->contractItem.getId().equals(item.getPurchaseContractItemId()))
					.collect(Collectors.toList());
			if(contractItemListById.size()<=0){
				throw new IllegalArgumentException("第"+(i+1)+"行列表信息：未查询到对应的采购合同管理信息");
			}
			TcgPurchaseContractItem tcgPurchaseContractItem = contractItemListById.get(0);

			//1、采购核销完整性 产生完整性的判断


			//2、子件核销数量 = 子件已核销数量+发票本次核销数量
			int subWriteOffNum = tcgPurchaseContractItem.getSubWriteOffNum() + item.getOffsetNum();
			//判断核销数量是否大于子件采购数量
			int countNum = subWriteOffNum - tcgPurchaseContractItem.getSubPurchaseNum();

			if(subWriteOffNum - tcgPurchaseContractItem.getSubPurchaseNum() == 0){//等于
				tcgPurchaseContractItem.setSubWriteOffState(1);//采购核销完整性（0否、1是）
			}
			tcgPurchaseContractItem.setSubWriteOffNum(subWriteOffNum);

			//修改采购合同单信息
			tcgPurchaseContractItemMapper.update(tcgPurchaseContractItem);
		}

		//修改信息
		tcgInvoiceOffsetMapper.update(entity);
		return R.ok();

	}

}
